//
//  ChatOptionView.m
//  supplyerIOS
//
//  Created by 穆相臣 on 2018/8/30.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "ChatOptionView.h"
@import AVFoundation;
@import AVKit;
@interface ChatOptionView ()<UITextViewDelegate>
{
    UIView * optionView;
    UIScrollView * functionView;
    UITextView * inputTextView;
    UIButton * voiceRecordButton;
    UIView * textLine;
    UIButton * textVoiceChange;
    UIButton * addImage;
    NSString * filePath;
}
@property (nonatomic, strong) AVAudioSession *session;
@property (nonatomic, strong) AVAudioRecorder *recorder;//录音器
@property (nonatomic, strong) AVAudioPlayer *player; //播放器
@property (nonatomic, strong) NSURL *recordFileUrl; //文件地址
@end

@implementation ChatOptionView

+(instancetype)optionView
{
    ChatOptionView * option = [[ChatOptionView alloc]initWithFrame:CGRectZero];
    return option;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:CGRectMake(0, ScreenHeight - 45, ScreenWidth, 45)])
    {
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
        line.backgroundColor = [UIColor colorFromHexCode:@"cccccc"];
        [self addSubview:line];
        
        self.backgroundColor = [UIColor whiteColor];
        
        
        inputTextView = [[UITextView alloc]initWithFrame:CGRectMake(5, 5, ScreenWidth - 10, 35)];
        inputTextView.scrollEnabled = YES;
        inputTextView.delegate = self;
        inputTextView.returnKeyType = UIReturnKeySend;
        [self addSubview:inputTextView];
        
        textLine = [[UIView alloc]initWithFrame:CGRectMake(5, 40, ScreenWidth - 10, 1)];
        textLine.backgroundColor = themeColor;
        [self addSubview:textLine];
        
//        voiceRecordButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 5, ScreenWidth - 100, 40)];
//        [voiceRecordButton addTarget:self action:@selector(voiceStart) forControlEvents:UIControlEventTouchDown];
//        [voiceRecordButton addTarget:self action:@selector(voiceEnd) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:voiceRecordButton];
//
//        textVoiceChange = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 45, 45)];
//        [textVoiceChange addTarget:self action:@selector(switchInput) forControlEvents:UIControlEventTouchUpInside];
//        textVoiceChange.backgroundColor = themeColor;
//        [self addSubview:textVoiceChange];
//
//        addImage = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 45, 0, 45, 45)];
//        [addImage addTarget:self action:@selector(addImgaeAction) forControlEvents:UIControlEventTouchUpInside];
//        addImage.backgroundColor = themeColor;
//        [self addSubview:addImage];
//
        voiceRecordButton.hidden = YES;
        inputTextView.hidden = NO;
        textLine.hidden = NO;
    }
    return self;
}



-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [self.delegate inputText:textView.text];
        [textView resignFirstResponder];
        textView.text = @"";
        [self heightCalculate];
        return NO;
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView
{
    [textView sizeToFit];
    [self heightCalculate];
}

-(void)heightCalculate
{
    if (textVoiceChange.selected)
    {
        // audio
        CGFloat upHeight = 45;
        
        self.frame = CGRectMake(0, ScreenHeight - upHeight - _kbHeight, ScreenWidth, upHeight);
        inputTextView.frame = CGRectMake(5, 5, ScreenWidth - 10, 30);
        textVoiceChange.frame = CGRectMake(0, upHeight - 45, 45, 45);
        addImage.frame = CGRectMake(ScreenWidth - 45, upHeight - 45, 45, 45);
        textLine.frame = CGRectMake(5, upHeight - 5, ScreenWidth - 10, 1);
    }
    else
    {
        // text
        [inputTextView sizeToFit];
        if (inputTextView.frame.size.height < 30) {
            inputTextView.frame = CGRectMake(5, 5, ScreenWidth - 10, 30);
        }
        inputTextView.frame = CGRectMake(5, 5, ScreenWidth - 10, inputTextView.frame.size.height);

        CGFloat upHeight = inputTextView.frame.size.height + 10;
        
        self.frame = CGRectMake(0, ScreenHeight - upHeight - _kbHeight, ScreenWidth, upHeight);
        textVoiceChange.frame = CGRectMake(0, upHeight - 45, 45, 45);
        addImage.frame = CGRectMake(ScreenWidth - 45, upHeight - 45, 45, 45);
        textLine.frame = CGRectMake(5, upHeight - 5, ScreenWidth - 10, 1);
    }
}

-(void)switchInput
{
    textVoiceChange.selected = !textVoiceChange.selected;
    [self heightCalculate];
    if (textVoiceChange.selected)
    {
        voiceRecordButton.hidden = NO;
        inputTextView.hidden = YES;
        textLine.hidden = YES;
    }
    else
    {
        voiceRecordButton.hidden = YES;
        inputTextView.hidden = NO;
        textLine.hidden = NO;
    }
}

-(void)voiceStart
{
    AVAudioSession *session =[AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if (session == nil) {
        
        NSLog(@"Error creating session: %@",[sessionError description]);
        
    }else{
        [session setActive:YES error:nil];
        
    }
    
    self.session = session;
    
    //1.获取沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    filePath = [path stringByAppendingString:@"/RRecord.wav"];
    unlink([filePath UTF8String]);
    //2.获取文件路径
    self.recordFileUrl = [NSURL fileURLWithPath:filePath];
    
    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
                                   // 音频格式
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    
    
    _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
    
    if (_recorder)
    {
        _recorder.meteringEnabled = YES;
        [_recorder prepareToRecord];
        [_recorder record];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self voiceEnd];
        });
    }
    else
    {
        NSLog(@"音频格式和文件存储格式不匹配,无法初始化Recorder");
    }
}

-(void)voiceEnd
{
    NSLog(@"停止录音");
    
    if ([self.recorder isRecording]) {
        [self.recorder stop];
    }
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath])
    {
        [self.delegate inputAudio:filePath];
    }
    else
    {
        
    }
}

-(void)dismiss
{
    [inputTextView resignFirstResponder];
}

-(void)addImgaeAction
{
    [self.delegate selectImage];
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
